import React, { useState } from 'react';
import { Table, Button, Input, DatePicker, Select, Form } from 'antd';
import dayjs from 'dayjs';
import { useEffect } from 'react';
import { api,queryList } from '../api/api';
import Url from '../api/url';
import * as XLSX from 'xlsx';
import { message } from 'antd';
import { Modal } from 'antd';

function PurFlowPage() {
  const [form] = Form.useForm();
  const [data,setData] = useState([]); // 空数据，表格结构先行
  const [pageSize, setPageSize] = useState(20); 

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const user = JSON.parse(localStorage.getItem('user'))
  const isAdmin = user?.USERID === 'admin';

  const columns = [
    { title: '摘要', dataIndex: 'SUMMARY', key: 'SUMMARY',width: 110 },
    { title: '日期', dataIndex: 'BILLINGDATE', key: 'BILLINGDATE',width: 105,render:(text) => text ? dayjs(text).format('YYYY-MM-DD') : '-'  },
    { title: '单据编号', dataIndex: 'BILLID', key: 'BILLID', width: 145 },
    { title: '单位名称', dataIndex: 'CUSTNAME', key: 'CUSTNAME', width: 180 },
    { title: '商品编号', dataIndex: 'PRODUCT_CODE', key: 'PRODUCT_CODE', width: 120 },
    { title: '商品名称', dataIndex: 'PRODUCT_NAME', key: 'PRODUCT_NAME', width: 150 },
    { title: '商品规格', dataIndex: 'PRODUCT_SPEC', key: 'PRODUCT_SPEC', width: 150 },
    { title: '生产厂家', dataIndex: 'MANUFACTURER', key: 'MANUFACTURER', width: 150 },
    { title: '单位', dataIndex: 'UNIT', key: 'UNIT', width: 80 },
    { title: '数量', dataIndex: 'QUANTITY', key: 'QUANTITY', width: 80 },
    { title: '含税单价', dataIndex: 'PRICE', key: 'PRICE', width: 100,render: (text) => text !== null && text !== undefined ? Number(text).toFixed(5) : '' },
    { title: '含税金额', dataIndex: 'AMOUNT', key: 'AMOUNT', width: 100,render: (text) => text !== null && text !== undefined ? Number(text).toFixed(2) : '' },
    { title: '批号', dataIndex: 'LOTNO', key: 'LOTNO', width: 100 },
    { title: '生产日期', dataIndex: 'PRODUCEDATE', key: 'PRODUCEDATE',width: 110, render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : '-' },
    { title: '有效期至', dataIndex: 'EXPIRYDATE', key: 'EXPIRYDATE',width: 110, render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : '-' },
    { title: '导入日期', dataIndex: 'CREATEDATE', key: 'CREATE_DATE',width: 110, render: (text) => text ? dayjs(text).format('YYYY-MM-DD') : '-' },
  ];

  const handleSearch = async () => {
    const fields = form.getFieldsValue()
    fields.startDate =  fields.startDate ? fields.startDate.format('YYYY-MM-DD') : null
    fields.endDate = fields.endDate ? fields.endDate.format('YYYY-MM-DD') : null
    fields.userId = user.USERID
    const dataList = await queryList({url:Url.getPurRecord,params:fields})
    setData(dataList)
  };

  const pageLoad = async () =>{
    const fields = form.getFieldsValue()
    fields.startDate =  fields.startDate ? fields.startDate.format('YYYY-MM-DD') : null
    fields.endDate = fields.endDate ? fields.endDate.format('YYYY-MM-DD') : null
    fields.userId = user.USERID
    const dataList = await queryList({url:Url.getPurRecord,params:fields})
    setData(dataList)
  }

  const deleteRecord = async () => {
    if (selectedRowKeys.length === 0) return;
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的${selectedRowKeys.length}条记录吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        const res = await api({url:Url.deleteRecord,data:{table:'tb_flow_pur_records',pkList:selectedRowKeys}})
            setData(data.filter(u => !selectedRowKeys.includes(u.PK)));
            setSelectedRowKeys([]);
            message.success(res.msg);
      },
    });
  }

  const handleExport = () => {
      // 字段映射
      const exportData = data.map(row => ({
        '摘要': row.SUMMARY,
        '日期': row.BILLINGDATE ? dayjs(row.BILLINGDATE).format('YYYY-MM-DD') : '',
        '单据编号': row.BILLID,
        '单位名称': row.CUSTNAME,
        '商品编号': row.PRODUCT_CODE,
        '商品名称': row.PRODUCT_NAME,
        '商品规格': row.PRODUCT_SPEC,
        '生产厂家': row.MANUFACTURER,
        '单位': row.UNIT,
        '数量': row.QUANTITY,
        '含税单价': row.PRICE !== null && row.PRICE !== undefined ? Number(row.PRICE).toFixed(2) : '',
        '含税金额': row.AMOUNT,
        '批号': row.LOTNO,
        '生产日期': row.PRODUCEDATE ? dayjs(row.PRODUCEDATE).format('YYYY-MM-DD') : '',
        '有效期至': row.EXPIRYDATE ? dayjs(row.EXPIRYDATE).format('YYYY-MM-DD') : '',
        '导入日期': row.CREATEDATE ? dayjs(row.CREATEDATE).format('YYYY-MM-DD') : ''
      }));
        const ws = XLSX.utils.json_to_sheet(exportData);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '采购流向');
        XLSX.writeFile(wb, '采购流向.xlsx');
    };

  useEffect(()=>{
      pageLoad()
    },[])

  

  return (
    <div style={{ padding: 16, background: '#f5f6fa' }}>
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 16, background: '#fff', padding: 16, borderRadius: 8, flexWrap: 'wrap' }}
        clearOnDestroy
        initialValues={{
          startDate: dayjs().startOf('month'),  // 设置为当月第一天
          endDate: dayjs(),  // 设置为当前日期
          manufacturer:'',
          productCode:'',
          productName:'',
        }}
      >
        <Form.Item label="生产厂家" name="manufacturer">
          <Input style={{ width: 160 }} />
        </Form.Item>
        <Form.Item label="商品编码" name="productCode">
          <Input style={{ width: 160 }} />
        </Form.Item>
        <Form.Item label="商品名称" name="productName">
          <Input style={{ width: 160 }} />
        </Form.Item>
        <Form.Item label="开始日期" name="startDate">
          <DatePicker style={{ width: 140 }} allowClear initialValues={dayjs('2025-06-01')} />
        </Form.Item>
        <Form.Item label="截至日期" name="endDate">
          <DatePicker style={{ width: 140 }} allowClear initialValues={dayjs('2025-06-02')} />
        </Form.Item>
 
        <Form.Item>
          <Button type="primary" onClick={handleSearch}>检索</Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={handleExport}>导出</Button>
        </Form.Item>
        <Form.Item>
            {isAdmin && (
              <Button danger onClick={deleteRecord} >
                删除
              </Button>
            )}
        </Form.Item>
      </Form>
      <Table
        columns={columns}
        dataSource={data}
        bordered
        pagination={{ 
          showSizeChanger:true,
          pageSizeOptions: ['10', '20', '50', '100'],
          pageSize: pageSize, showTotal: total => `共${total}条`,
        onShowSizeChange: (current, size) => {
            setPageSize(size);
          }
        }}
        style={{ background: '#fff', borderRadius: 8 }}
        scroll={{ x: '100%', y: 'calc(100vh - 260px)' }}
        rowKey={'PK'}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
      />
    </div>
  );
}

export default PurFlowPage;


